package com.fuhao.pay.callback.servjce;

import com.fuhao.pay.callback.template.AbstractPayCallbackTemplate;
import com.fuhao.pay.callback.template.factory.TemplateFactory;
import com.fuhao.wx.WXPayClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@Slf4j
public class PayAsynCallbackService {
	private static final String UNIONPAYCALLBACK_TEMPLATE = "unionPayCallbackTemplate";
	private static final String ALIPAYCALLBACK_TEMPLATE = "aliPayCallbackTemplate";
	private static final String WXPAYCALLBACK_TEMPLATE = "wxPayCallbackTemplate";

	@Autowired
	private WXPayClient wxPayClient;
	/**
	 * 银联异步回调接口执行代码
	 *
	 * @param req
	 * @param resp
	 * @return
	 */
	@PostMapping("/unionPayAsynCallback")
	public void unionPayAsynCallback(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		AbstractPayCallbackTemplate abstractPayCallbackTemplate = TemplateFactory
				.getPayCallbackTemplate(UNIONPAYCALLBACK_TEMPLATE);
		String respCode = abstractPayCallbackTemplate.asyncCallBack(req, resp, null);
		Integer code = Integer.parseInt(respCode);
		resp.getWriter().print(code);//返回给银联服务器http 200  状态码
		//TODO 此处有BUG 不断回调，记录
	}

	/**
	 * 支付宝异步回调接口执行代码
	 *
	 * @return
	 */
	@PostMapping("/aliPayAsynCallback")
	public String unionPayAsynCallback(@RequestParam Map<String, String> params,HttpServletResponse resp) throws Exception {
		AbstractPayCallbackTemplate abstractPayCallbackTemplate = TemplateFactory
				.getPayCallbackTemplate(ALIPAYCALLBACK_TEMPLATE);
		return abstractPayCallbackTemplate.asyncCallBack(null, null,params);
	}

	/**
	 * 微信异步回调接口执行代码
	 *
	 * @return
	 */
	@PostMapping("/wxPayAsynCallback")
	public void wxPayAsynCallback(HttpServletRequest request,HttpServletResponse resp) throws Exception {
		log.info(">>>>>>>>>>>微信回调开始<<<<<<<<<<<<<<");
		resp.setContentType("text/xml");
		AbstractPayCallbackTemplate abstractPayCallbackTemplate = TemplateFactory
				.getPayCallbackTemplate(WXPAYCALLBACK_TEMPLATE);
		Map<String, String> params = wxPayClient.getNotifyParameter(request);
		String respXml = abstractPayCallbackTemplate.asyncCallBack(null, null, params);
		resp.getWriter().write(respXml);
		resp.flushBuffer();
		log.info(">>>>>>>>>>>微信回调结束<<<<<<<<<<<<<<");
	}
}
